package org.emergency.framework.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

import sun.misc.BASE64Encoder;

/**
 * 密码工厂
 * 暂时支持MD5和SHA，默认使用MD5
 * @author Zheng
 */
public class PasswordUtil implements PasswordEncoder{
	private final Logger LOG = Logger.getLogger(this.getClass());
	
	public final static String TYPE_MD5 = "MD5";
	public final static String TYPE_SHA = "SHA";
	
	private String type;
	private MessageDigest messageDigest;
	private static PasswordUtil passwordUtil;
	//默认使用MD5加密
	private PasswordUtil(){
		this(TYPE_MD5);
	}
	private PasswordUtil(String type){
		this.type=type;
		try{
			messageDigest = MessageDigest.getInstance(type);
		}catch(NoSuchAlgorithmException e){
			e.printStackTrace();
			LOG.error("No Such Algorithm!");
		}
	}

	public static synchronized PasswordUtil getInstance(){
		return getInstance("MD5");
	}	
	
	public static synchronized PasswordUtil getInstance(String type){
		return passwordUtil = new PasswordUtil(type);
	}

	public String encode(String password) {
		try{
			messageDigest.update(password.trim().getBytes("UTF-8"));
		}catch(Exception e){
			e.printStackTrace();
			LOG.error("Message Digest Update Error.");
		}
		byte[] digest=messageDigest.digest();
		BASE64Encoder base64 = new BASE64Encoder();
		return base64.encode(digest);

	}
}
